package cn.gson.crm.config;

import cn.gson.crm.exception.MiniApiException;
import cn.gson.crm.model.domain.UserEntity;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限URL拦截器
 * 
 * @author gson
 *
 */
@Component
public class WechatMiniInterceptor implements HandlerInterceptor {
	private final String tokenHeader = "Authorization";

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

		String token  = httpServletRequest.getHeader(tokenHeader);
		if(!StringUtils.isEmpty(token)){
			String userInfo = stringRedisTemplate.opsForValue().get(token);
			if(StringUtils.isEmpty(userInfo)){
				throw new MiniApiException("请先登录！");
			}else{
				//转成需要的用户对象
				UserEntity user =	JSONObject.parseObject(userInfo, UserEntity.class);
				httpServletRequest.getSession().setAttribute("userInfo",user);
				return true;
			}
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

	}
}
